import logging
from typing import Any, Dict, Optional
from opensearchpy import OpenSearch, NotFoundError, OpenSearchException

logger = logging.getLogger("opensearch_client")

class OpenSearchClient:
    """
    OpenSearch基础操作封装，支持增删改查，便于后续扩展混合检索。
    """
    def __init__(self, hosts: Optional[list[str]] = None, http_auth: Optional[tuple[str, str]] = None) -> None:
        self.hosts = hosts or ["http://localhost:9200"]
        self.http_auth = http_auth
        try:
            self.client = OpenSearch(hosts=self.hosts, http_auth=self.http_auth)
            logger.info(f"OpenSearch连接成功: hosts={self.hosts}")
        except Exception as e:
            logger.error(f"OpenSearch连接失败: {e}")
            raise

    def create_index(self, index: str, body: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        try:
            return self.client.indices.create(index=index, body=body or {})
        except OpenSearchException as e:
            logger.error(f"创建索引失败: {e}")
            raise

    def delete_index(self, index: str) -> Dict[str, Any]:
        try:
            return self.client.indices.delete(index=index)
        except NotFoundError:
            logger.warning(f"索引不存在: {index}")
            return {"acknowledged": True, "message": "index not found"}
        except OpenSearchException as e:
            logger.error(f"删除索引失败: {e}")
            raise

    def add_doc(self, index: str, doc_id: str, body: Dict[str, Any]) -> Dict[str, Any]:
        try:
            return self.client.index(index=index, id=doc_id, body=body)
        except OpenSearchException as e:
            logger.error(f"添加文档失败: {e}")
            raise

    def get_doc(self, index: str, doc_id: str) -> Optional[Dict[str, Any]]:
        try:
            return self.client.get(index=index, id=doc_id)
        except NotFoundError:
            logger.warning(f"文档不存在: {doc_id}")
            return None
        except OpenSearchException as e:
            logger.error(f"获取文档失败: {e}")
            raise

    def update_doc(self, index: str, doc_id: str, body: Dict[str, Any]) -> Dict[str, Any]:
        try:
            return self.client.update(index=index, id=doc_id, body={"doc": body})
        except OpenSearchException as e:
            logger.error(f"更新文档失败: {e}")
            raise

    def delete_doc(self, index: str, doc_id: str) -> Dict[str, Any]:
        try:
            return self.client.delete(index=index, id=doc_id)
        except NotFoundError:
            logger.warning(f"文档不存在: {doc_id}")
            return {"result": "not_found"}
        except OpenSearchException as e:
            logger.error(f"删除文档失败: {e}")
            raise 